package edu.caltech.cs.techerlink;

import java.io.IOException;
import java.util.Date;
import java.util.logging.Logger;
import javax.jdo.PersistenceManager;
import javax.servlet.http.*;
import com.google.appengine.api.users.User;
import com.google.appengine.api.users.UserService;
import com.google.appengine.api.users.UserServiceFactory;

@SuppressWarnings("serial")
public class PostServlet extends HttpServlet {
	private static final Logger log = Logger
			.getLogger(PostServlet.class.getName());

	@Override
	public void doPost(HttpServletRequest req, HttpServletResponse resp)
			throws IOException {
		UserService userService = UserServiceFactory.getUserService();
		User user = userService.getCurrentUser();

		String content = req.getParameter("content");
		if (content.length() >= 150) {
			content = content.substring(0, 150);
		}
		content = content.replaceAll("\\<.*?>", "");

		Date date = new Date();
		Post post = new Post(user, content, date);

		PersistenceManager pm = PMF.get().getPersistenceManager();
		try {
			pm.makePersistent(post);
			log.info("Post " + post.getKey() + " successfully created." + pm.isClosed() + " " + pm);
		} finally {
			pm.close();
		}

		resp.sendRedirect("/");
	}
}